package Security;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Model.User;

/**
 * Servlet Filter implementation class AdminFilter
 */
public class AdminFilter implements Filter {

    /**
     * Default constructor. 
     */
    public AdminFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
		HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        //System.out.println(req.getRequestURI().substring(12));
        User currentuser = (User) session.getAttribute("sessionlogin");
        if(currentuser == null){
        	System.out.println("Vao Filter");
            session.setAttribute("url", "/SHOPCH4/Admin/");
            rep.sendRedirect("../login.jsp");
            return;
        }else{
        	System.out.println("Vao filter 2");
        		System.out.println("Quyen: "+currentuser.getQuyen().getTenQuyen());
	        	if(currentuser.getQuyen().getTenQuyen()!=1){
		            rep.sendRedirect("../unauthorization.jsp");
		            return;
	        	}
	        	else{
		            chain.doFilter(req, rep);
		            return;
	        	}
        }
	}
	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
